package com.gds.config.webscoket;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/***
 * 模拟实时点对点(针对某个用户)推送消息
 * @author Administrator
 */
@ServerEndpoint(value ="/webSocket/{userId}")
@Component
public class WebSocketDemo {
    private static ConcurrentHashMap<String, Session> userMap  = new ConcurrentHashMap<>(20);
    private Session session;
    private String  userid;

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
       this.session =session;
       this.userid =userId;
        userMap.put(this.userid,this.session);
        System.out.println("已连接");
    }

    @OnClose
    public void onClose() throws IOException {
        userMap.remove(userid);
    }

    /***
     * 客户端向服务器发送消息 服务器收到的消息
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        //收到消息告诉客户端已经收到
        sendMessageTo(userid, "服务器已收到你的消息");
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /****
     * 给某个用户
     * @param userid
     * @param message
     * @throws IOException
     */
    public static void   sendMessageTo(String userid, String message) throws IOException {
        if(userMap.containsKey(userid)){
            userMap.get(userid).getAsyncRemote().sendText(message);
        }
    }


}
